from flask import Flask, render_template, request, session, jsonify
import pymysql
from mysql import mysql

app = Flask(__name__)
app.config["SECRET_KEY"] = 'TPmi4aLWRbyVq8zu9v82dWYW1'


@app.route('/')
def n():
    return 'hello world'


@app.route('/index')
def index():
    return render_template('index_new.html')


@app.route('/regist', methods=['POST', 'GET'])
def regist():
    if request.method == 'POST':
        get_username = request.form.get('User')
        get_password = request.form.get('Password')
        print(get_username, get_password)
        a2 = mysql(sql="select exists(select * from users where username = '%s')" % (get_username))
        if a2.username_query_exist() == 'exist':
            return jsonify('账号已存在')
        elif a2.username_query_exist() == 'not exist':
            a4 = mysql(sql="insert into users(username,password)values('%s','%s')" % (get_username, get_password))
            print(a4.insert_username_password())
            return jsonify('注册成功')
        else:
            print('unknown error')
    else:
        pass

    return render_template('regist_new.html')


@app.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'POST':
        get_username = request.form.get('User')
        get_password = request.form.get('Password')
        print(get_username, get_password)
        a2 = mysql(sql="select exists(select * from users where username = '%s')" % (get_username))
        if a2.username_query_exist() == 'exist':
            a3 = mysql(sql="select password from users where username = '%s'" % (get_username))
            print(a3.username_query_password())
            if a3.username_query_password() == get_password:
                session["username"] = request.form.get('User')
                return jsonify('登录成功')
            elif a3.username_query_password() != get_password:
                return jsonify('密码不正确')
            else:
                return 'unknown error'
        elif a2.username_query_exist() == 'not exist':
            a4 = mysql(sql="insert into users(username,password)values('%s','%s')" % (get_username, get_password))
            print(a4.insert_username_password())
            return jsonify('账号不存在')
        else:
            print('unknown error')
    else:
        pass

    return render_template('login_new.html')


@app.route('/score', methods=['POST', 'GET'])
def score():
    if request.method == 'POST':
        true = request.form.get('true')
        error = request.form.get('error')
        get_username = session['username']
        over_time = request.form.get('over_time')
        score = int(true) + int(error)
        a5 = mysql(
            sql="insert into score(username,score,true_text,error_text,text_time)values('%s','%s','%s','%s','%s')" % (
                get_username, score, true, error, over_time))
        print(a5.insert_data())
        print(get_username, over_time, true, error, score)
    else:
        pass
    return 'score cg'


@app.route('/look', methods=['POST', 'GET'])
def look():
    if request.method == 'POST':
        get_username = session['username']
        db = pymysql.connect(host='127.0.0.1', user='root', password='123456', database='typing', charset='utf8')
        cursor = db.cursor()
        cursor.execute("select true_text from score where username ='%s'  order by true_text" % (get_username))
        b = cursor.fetchall()
        username = []

        score = []
        for row in b:
            second = row[0]
            username.append(get_username)
            score.append(second)

        test = {
            'username': username,
            'score': score
        }
        print(test)
        db.close()
        return test

    return render_template('look.html')


@app.route('/upload', methods=['POST', 'GET'])
def upload():
    if request.method == 'POST':
        username = session['username']
        over_time = request.form.get('over_time')
        text_name = request.form.get('text_name')
        print(username, text_name, over_time)
        a2 = mysql(sql="select exists(select * from text_data where username = '%s')" % (username))
        exist = a2.username_query_exist()
        print(exist)
        if exist == 'exist':
            a8 = mysql(sql="update text_data set over_time = '%s',text_name='%s' where username = '%s'" % (
                over_time, text_name, username))
            a8.updata_data()
        elif exist == 'not exist':
            a5 = mysql(sql="insert into text_data(username,over_time,text_name)values('%s','%s','%s')" % (
                username, over_time, text_name))
            print(a5.insert_data())
        else:
            print('shibai')
    return render_template('text_data_new.html')


@app.route('/updata', methods=['POST', 'GET'])
def updata():
    if request.method == 'POST':
        username = session['username']
        b1 = mysql(sql="select text_name from text_data where username = '%s'" % (username))
        text_name = b1.username_query_password()

        b2 = mysql(sql="select over_time from text_data where username = '%s'" % (username))
        over_time = b2.username_query_password()

        b3 = mysql(sql="select text_content from text where text_name = '%s'" % (text_name))
        text_content = b3.username_query_password()

        b = []
        for i in text_content.split("."):
            b.append(i)
        # print(text_name, over_time, b)
        all = {
            'over_time': over_time,
            'text_content': b,
        }
        return all


@app.route('/topic', methods=['POST', 'GET'])
def topic():
    if request.method == 'POST':
        a9 = mysql(sql="select text_name from text")
        all_text = a9.query_all()
        topic = []
        for i in all_text:
            topic.append(i[0])
        print(topic)
        topic = {
            'topic': topic
        }
        return topic
    return render_template('text_data_new.html')


@app.route('/topictext', methods=['POST', 'GET'])
def topictext():
    if request.method == 'POST':
        text_name = request.form.get('value')
        a3 = mysql(sql="select text_content from text where text_name = '%s'" % (text_name))

        text_content = a3.username_query_password()
        text = {
            ' text': text_content
        }
        return text


@app.route('/uploadtext', methods=['POST', 'GET'])
def uploadtext():
    if request.method == 'POST':
        name = request.form.get('text_name')
        content = request.form.get('text_content')
        print(name, content)
        a2 = mysql(sql='select exists(select * from text where text_name = "%s")' % (name))
        exist = a2.username_query_exist()
        if exist == 'exist':
            return 'text_name exist'
        elif exist == 'not exist':
            a4 = mysql(sql='insert into text(text_name,text_content)values("%s","%s")' % (name, content))
            print(a4.insert_username_password())
            return 'cg'
        return 'gg'
    return render_template('uploadtext.html')


@app.route('/uploadalltext', methods=['POST', 'GET'])
def uploadalltext():
    if request.method == 'POST':
        a1 = mysql(sql='select * from text')
        b = a1.query_all()
        # print(b)
        name = []
        content = []
        for i in b:
            name.append(i[0])
            content.append(i[1])

        # print(name)
        # print(content)
        text = {
            'name': name,
            'content': content
        }

        return text


@app.route('/deletetext', methods=['POST', 'GET'])
def deletetext():
    if request.method == 'POST':
        name = request.form.get('text_name')
        print(name)
        a6 = mysql(sql="delete from text where text_name = '%s'" % (name))
        print(a6.delete_table_data())
        return {"name": 'delete cg'}


@app.route('/loginlook', methods=['POST', 'GET'])
def loginlook():
    if request.method == 'POST':
        a7 = mysql(sql='select * from score order by true_text desc limit 10')
        b = a7.query_all()

        name = []
        text = []
        for i in b:
            name.append(i[0])
            text.append(i[2])
        print(text)
        text.reverse()
        name.reverse()
        return {
            'text': text,
            'name': name
        }


if __name__ == '__main__':
    app.run()
